import React, { useRef, useState } from 'react';
import KPageHeader from '@/components/KPageHeader';
import { ActionType, ProColumnType } from '@ant-design/pro-table';
import { apiRole, apiSystemPermissions } from '@/api/system/roles.api';
import KTable from '@/components/KTable';
import { useRequest } from 'ahooks';
import { DrawerForm } from '@ant-design/pro-form';
import { Button, Form, Input, message, Popconfirm, Space } from 'antd';
import MultiList from '@/components/MultiList';
import { history } from 'umi';

// 添加权限
const DialogFormAddPermission = (role: API.Role) => {
  const [visible, setVisible] = useState(false);
  const { data, run: getData, loading } = useRequest(apiSystemPermissions, {
    manual: true,
    cacheKey: 'system.permissions',
  });
  const { run: addPermissions } = useRequest(apiRole.addPermissions, {
    manual: true,
    onSuccess: () => {
      message.success('添加成功');
    },
  });

  const onVisibleChange = async (visible: boolean) => {
    if (visible) {
      await getData();
    }
    setVisible(visible);
  };

  // 表单提交
  const onFormSubmit = async (formData: any) => {
    await addPermissions([role.id], formData.permissions);
  };
  return (
    <DrawerForm<API.Role>
      title={'添加权限'}
      trigger={<a>添加权限</a>}
      initialValues={{
        ...role,
      }}
      onVisibleChange={onVisibleChange}
      onFinish={onFormSubmit}
    >
      <Form.Item label={'角色名'} name={'name'} required={true}>
        <Input readOnly={true} />
      </Form.Item>

      <Form.Item label={'添加权限'} name={'permissions'} required={true}>
        <MultiList
          visible={visible}
          loading={loading}
          options={
            data?.map(item => ({
              id: item.id,
              name: item.name,
              remark: item.title,
            })) ?? []
          }
          mode={1}
          columns={['权限名', '描述']}
          onSearch={v => getData({ search: v })}
        />
      </Form.Item>
    </DrawerForm>
  );
};

// 删除按钮
const DeleteButton = (props: { data: API.Role; onSuccess: () => void }) => {
  const { run } = useRequest(apiRole.delete, {
    manual: true,
    onSuccess: () => {
      message.success('删除成功');
      props.onSuccess();
    },
  });
  return (
    <Popconfirm
      title={'确定要删除此行数据?'}
      onConfirm={() => run([props.data.id])}
    >
      <a>删除</a>
    </Popconfirm>
  );
};

export default () => {
  const table = useRef<ActionType>();
  const columns: ProColumnType<API.Role>[] = [
    {
      title: '角色名',
      dataIndex: 'name',
      render: (value, record) => (
        <a onClick={() => history.push(`roles/${record.id}`)}>{value}</a>
      ),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      hideInSearch: true,
    },
    {
      title: '操作',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => (
        <Space>
          <DialogFormAddPermission {...record} />
          <DeleteButton
            data={record}
            onSuccess={() => table.current?.reload()}
          />
        </Space>
      ),
    },
  ];
  return (
    <>
      <KPageHeader title={'角色管理'} showBack={false} />

      <KTable
        actionRef={table}
        rowKey={'id'}
        request={apiRole.getList}
        columns={columns}
      />
    </>
  );
};
